package com.bytedance.improvingroad.binder.proxy

import android.os.IBinder
import android.os.Parcel
import android.os.RemoteException
import com.bytedance.improvingroad.binder.Book
import com.bytedance.improvingroad.binder.server.BookManager
import com.bytedance.improvingroad.binder.server.Stub



/**
 * Created by chenxiong
 * date 12/14/21
 */
class Proxy(private val remote: IBinder): BookManager {
    companion object {
        const val DESCRIPTOR = "com.bytedance.improvingroad.binder.server.BookManager"
    }

    override fun addBook(book: Book) {
        val data: Parcel = Parcel.obtain()
        val replay: Parcel = Parcel.obtain()

        try {
            data.writeInterfaceToken(DESCRIPTOR)
            data.writeInt(1)
            book.writeToParcel(data, 0)
            remote.transact(Stub.TRANSAVTION_addBook, data, replay, 0)
            replay.readException()
        } finally {
            replay.recycle()
            data.recycle()
        }
    }

    @Throws(RemoteException::class)
    override fun getBooks(): List<Book?>? {
        val data = Parcel.obtain()
        val replay = Parcel.obtain()
        return try {
            data.writeInterfaceToken(DESCRIPTOR)
            remote.transact(Stub.TRANSAVTION_getBooks, data, replay, 0)
            replay.readException()
            replay.createTypedArrayList(Book.CREATOR)
        } finally {
            replay.recycle()
            data.recycle()
        }
    }

    override fun asBinder(): IBinder {
        return remote
    }
}